<template>
  <div class="app-container" style="padding: 8px;">
    <div class="head-container">
      <el-form ref="form" :model="form" :rules="rules" style="margin-top: 6px;" size="small" label-width="90px">
        <el-form-item label="输入String" prop="body">
          <el-input v-model="form.body" style="weight:75%;" rows="10" type="textarea"/>
        </el-form-item>
        <el-form-item label="">
          <el-button :loading="doSubmitLoading" size="medium" type="primary" @click="doSubmit">生成</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="body-container" style="display:inline-block;margin-bottom:20px;">
    <pre>
        {{ bodyContainer }}
      </pre>
    </div>


  </div>

</template>

<script>
    import {createJsonFromKey} from '@/api/code-tools'

    export default {
        components: {},
        data() {
            return {
                form: {
                    body: ''

                },
                bodyContainer: '',
                formatJson: '',
                doSubmitLoading: false,
                rules: {
                    body: [
                        {required: true, message: '字符串不能为空', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            doSubmit() {
                const json = this.form.body;
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        if (json === null || json === undefined) {
                            this.$message({
                                message: 'json为空',
                                type: 'error'
                            })
                        } else {
                            createJsonFromKey(this.form.body
                            ).then(res => {
                                this.form.body = JSON.stringify(res.data)
                                console.log(res.data)
                            }).catch(err => {
                                this.loading = false
                                console.log(err)
                            })
                        }
                    } else {
                        return false
                    }
                })


            },
            doFormat() {
                this.doCheck();
            },
            doCheck() {
                const json = this.form.body;
                if (!json) {
                    return
                }
                this.showCheckResult(json)
            },
            showCheckResult(json) {
                try {
                    const jsonString = JSON.parse(json)
                    this.form.body = JSON.stringify(jsonString, null, 4);
                } catch (e) {
                    this.$message({
                        message: 'json格式不正确',
                        type: 'error'
                    })
                }
            }
        }
    }
</script>

<style scoped>
</style>
